<template>
  <div class="art-order-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索订单ID/作品名称/画家"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增订单
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredOrders" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="orderId" label="订单ID" width="180" sortable align="center" />
      <el-table-column prop="artwork" label="作品名称" width="150">
        <template #default="{ row }">
          <el-tag effect="plain" type="info">
            {{ row.artwork }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="artist" label="画家" width="140">
        <template #default="{ row }">
          <el-tag effect="plain" :type="typeTagType[row.artStyle]">
            {{ row.artist }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="140" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]" effect="light">
            {{ statusOptions.find(s => s.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="金额" width="120" align="center">
        <template #default="{ row }">
          <span style="color: #E6A23C;">¥{{ row.price.toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderDate" label="下单日期" width="140" sortable />
      <el-table-column prop="deliveryDays" label="交付倒计时" width="120" align="center">
        <template #default="{ row }">
          <span :style="row.deliveryDays <= 3 ? 'color: #F56C6C;' : 'color: #67C23A;'">
            {{ row.deliveryDays }}天
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="customer" label="客户姓名" width="150" />
      <el-table-column prop="address" label="配送地址" width="160">
        <template #default="{ row }">
          <div class="note-preview">{{ row.address }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.orderId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑订单信息' : '新增油画订单'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="订单ID" prop="orderId">
          <el-input 
            v-model="formData.orderId" 
            :disabled="isEditMode"
            placeholder="ART+8位日期+3位序列"
          />
        </el-form-item>
        <el-form-item label="作品名称" prop="artwork">
          <el-input 
            v-model="formData.artwork"
            placeholder="例：星月夜"
          />
        </el-form-item>
        <el-form-item label="艺术风格" prop="artStyle">
          <el-select 
            v-model="formData.artStyle"
            placeholder="请选择风格"
            style="width: 100%"
          >
            <el-option
              v-for="item in artStyles"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select 
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="1000"
            :max="1000000"
            controls-position="right"
            style="width: 100%"
          >
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="下单日期" prop="orderDate">
          <el-date-picker
            v-model="formData.orderDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="交付期限" prop="deliveryDays">
          <el-input-number
            v-model="formData.deliveryDays"
            :min="1"
            :max="30"
            controls-position="right"
            style="width: 100%"
          >
            <template #append>天</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="客户姓名" prop="customer">
          <el-input 
            v-model="formData.customer"
            placeholder="请输入客户姓名"
          />
        </el-form-item>
        <el-form-item label="配送地址" prop="address">
          <el-input 
            type="textarea"
            v-model="formData.address" 
            rows="3"
            placeholder="请输入详细地址"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 艺术风格配置
const artStyles = [
  '印象派',
  '古典主义',
  '抽象表现主义',
  '超现实主义',
  '立体主义',
  '现实主义',
  '波普艺术'
]

// 订单状态选项
const statusOptions = [
  { value: 'pending', label: '待付款' },
  { value: 'paid', label: '已付款' },
  { value: 'shipped', label: '已发货' },
  { value: 'completed', label: '已完成' }
]

// 标签样式映射
const typeTagType = {
  '印象派': 'primary',
  '古典主义': 'success',
  '抽象表现主义': 'warning',
  '超现实主义': 'danger',
  '立体主义': 'info',
  '现实主义': '',
  '波普艺术': 'primary'
}

const statusTagType = {
  'pending': 'warning',
  'paid': 'success',
  'shipped': 'info',
  'completed': ''
}

// 初始订单数据（7条示例）
const orders = ref([
  {
    orderId: 'ART20240526001',
    artwork: '星月夜',
    artist: '文森特·梵高',
    artStyle: '后印象派',
    status: 'paid',
    price: 4500000,
    orderDate: '2024-05-20',
    deliveryDays: 5,
    customer: '张艺谋',
    address: '北京市朝阳区798艺术区'
  },
  {
    orderId: 'ART20240526002',
    artwork: '格尔尼卡',
    artist: '巴勃罗·毕加索',
    artStyle: '立体主义',
    status: 'shipped',
    price: 2000000,
    orderDate: '2024-05-15',
    deliveryDays: 2,
    customer: '李安',
    address: '上海市浦东新区世纪大道'
  },
  {
    orderId: 'ART20240526003',
    artwork: '记忆的永恒',
    artist: '萨尔瓦多·达利',
    artStyle: '超现实主义',
    status: 'completed',
    price: 1800000,
    orderDate: '2024-05-10',
    deliveryDays: -3,
    customer: '王家卫',
    address: '广州市天河区珠江新城'
  },
  {
    orderId: 'ART20240526004',
    artwork: '日出·印象',
    artist: '克劳德·莫奈',
    artStyle: '印象派',
    status: 'pending',
    price: 3500000,
    orderDate: '2024-05-25',
    deliveryDays: 7,
    customer: '陈凯歌',
    address: '杭州市西湖区西溪湿地'
  },
  {
    orderId: 'ART20240526005',
    artwork: '戴珍珠耳环的少女',
    artist: '约翰内斯·维米尔',
    artStyle: '古典主义',
    status: 'paid',
    price: 2800000,
    orderDate: '2024-05-22',
    deliveryDays: 4,
    customer: '贾樟柯',
    address: '成都市锦江区太古里'
  },
  {
    orderId: 'ART20240526006',
    artwork: '呐喊',
    artist: '爱德华·蒙克',
    artStyle: '表现主义',
    status: 'shipped',
    price: 3200000,
    orderDate: '2024-05-18',
    deliveryDays: 1,
    customer: '姜文',
    address: '深圳市南山区科技园'
  },
  {
    orderId: 'ART20240526007',
    artwork: '向日葵',
    artist: '文森特·梵高',
    artStyle: '后印象派',
    status: 'pending',
    price: 3800000,
    orderDate: '2024-05-24',
    deliveryDays: 6,
    customer: '冯小刚',
    address: '武汉市武昌区东湖路'
  }
])

// 计算交付倒计时
const calculateDeliveryDays = (order) => {
  const orderDate = new Date(order.orderDate)
  const deliveryDate = new Date(orderDate.setDate(orderDate.getDate() + order.deliveryDays))
  const diffTime = deliveryDate - new Date()
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

// 自动更新倒计时
orders.value.forEach(order => {
  order.deliveryDays = calculateDeliveryDays(order)
})

// 搜索功能
const searchText = ref('')
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    return Object.values(order).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
  )})
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  orderId: '',
  artwork: '',
  artist: '',
  artStyle: '印象派',
  status: 'pending',
  price: 1000000,
  orderDate: new Date().toISOString().split('T')[0],
  deliveryDays: 7,
  customer: '',
  address: ''
})

// 表单验证规则
const formRules = {
  orderId: [
    { required: true, message: '请输入订单ID', trigger: 'blur' },
    { pattern: /^ART\d{8}\d{3}$/, message: '格式要求：ART+8位日期+3位序列', trigger: 'blur' }
  ],
  artwork: [
    { required: true, message: '请输入作品名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度2-30个字符', trigger: 'blur' }
  ],
  artStyle: { required: true, message: '请选择艺术风格', trigger: 'change' },
  price: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 1000, max: 10000000, message: '金额范围1,000-10,000,000', trigger: 'blur' }
  ],
  customer: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度2-20个字符', trigger: 'blur' }
  ]
}

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (orderId) => {
  ElMessageBox.confirm('确定删除该订单？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orders.value = orders.value.filter(u => u.orderId !== orderId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = orders.value.findIndex(u => u.orderId === formData.orderId)
    orders.value.splice(index, 1, { 
      ...formData,
      deliveryDays: calculateDeliveryDays(formData)
    })
  } else {
    if (orders.value.some(u => u.orderId === formData.orderId)) {
      return ElMessage.warning('订单ID已存在')
    }
    orders.value.push({ 
      ...formData,
      deliveryDays: calculateDeliveryDays(formData)
    })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '新增成功')
}

const resetForm = () => {
  formData.orderId = ''
  formData.artwork = ''
  formData.artist = ''
  formData.artStyle = '印象派'
  formData.status = 'pending'
  formData.price = 1000000
  formData.orderDate = new Date().toISOString().split('T')[0]
  formData.deliveryDays = 7
  formData.customer = ''
  formData.address = ''
}
</script>

<style scoped lang="scss">
.art-order-management {
  padding: 24px;
  background: #ffffff;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
    border: 1px solid #f0f0f0;
  }

  :deep(.table-header) th {
    background-color: #f8f9fa !important;
    color: #606266;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    background: #ffffff;
    border: 1px solid #f0f0f0;
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }

  .note-preview {
    display: -webkit-box;
    .note-preview {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2; // 添加标准属性
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
    color: #606266;
  }
}

.el-dialog {
  border-radius: 12px;
  background: #ffffff;
  
  .el-dialog__header {
    border-bottom: 1px solid #f0f0f0;
    margin: 0 24px;
    padding: 24px 0 16px;
    color: #303133;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
    color: #606266;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
  :deep(.el-form-item__label) {
    color: #606266;
  }
}
</style>